#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import sys

# 设置Django环境
current_dir = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, current_dir)
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'wealth_backend.settings')

# 导入Django并设置
import django  # type: ignore
django.setup()

from data_service.models import FundInfo  # type: ignore
from data_service.akshare_service import akshare_service  # type: ignore

def update_fund_details():
    """更新基金详细信息"""
    # 获取前10个基金进行测试
    funds = FundInfo.objects.all()[:10]
    
    updated_count = 0
    failed_count = 0
    
    for fund in funds:
        try:
            # 只使用东方财富数据源，避免雪球数据源的MiniRacer错误
            fund_detail = akshare_service.fetch_fund_detail(fund.fund_code)
            
            if fund_detail:
                # 更新基金信息
                if fund_detail.get('fund_company'):
                    fund.fund_company = fund_detail['fund_company']
                if fund_detail.get('fund_manager'):
                    fund.fund_manager = fund_detail['fund_manager']
                if fund_detail.get('establishment_date'):
                    fund.establishment_date = fund_detail['establishment_date']
                if fund_detail.get('fund_size'):
                    fund.fund_size = akshare_service._parse_decimal(fund_detail['fund_size'])
                
                fund.save()
                updated_count += 1
                print(f"更新基金 {fund.fund_code} 成功")
            else:
                failed_count += 1
                print(f"获取基金 {fund.fund_code} 详细信息失败")
                
        except Exception as e:
            failed_count += 1
            print(f"更新基金 {fund.fund_code} 失败: {e}")
    
    print(f"\n更新完成: 成功 {updated_count} 个，失败 {failed_count} 个")

if __name__ == '__main__':
    update_fund_details()